package com.zzjc.web.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzjc.web.entity.Alarm;
import com.zzjc.web.entity.Device;
import com.zzjc.web.mapper.AlarmDao;
import com.zzjc.web.mapper.DeviceDao;
import com.zzjc.web.service.AlarmService;
import com.zzjc.web.util.ApiResponse;
import com.zzjc.web.util.DateUtils;
import com.zzjc.web.util.ResponseUtil;
import com.zzjc.web.util.StringKit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

@Slf4j
@Service
public class AlarmServiceImpl implements AlarmService {

    @Autowired
    private AlarmDao alarmDao;

    @Autowired
    private DeviceDao deviceDao;


    private static final String CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    @Override

    public ApiResponse addAlarm(Alarm alarm) {
        if (StringKit.notBlank(alarm.getDeviceId())) {
            try {
                Device iDevice = deviceDao.getDeviceById(alarm.getDeviceId());
                if (iDevice == null) {
                    return ResponseUtil.error("摄像头不存在");
                } else {
                    String deviceName = iDevice.getDeviceName();
                    alarm.setAlarmTime(DateUtils.getNowDate());
                    // 获取当前时间戳（毫秒级）
                    long timestamp = System.currentTimeMillis();
                    // 生成 6 位随机字符串
                    StringBuilder randomPart = new StringBuilder();
                    ThreadLocalRandom random = ThreadLocalRandom.current();
                    for (int i = 0; i < 6; i++) {
                        int index = random.nextInt(CHARACTERS.length());
                        randomPart.append(CHARACTERS.charAt(index));
                    }
                    // 拼接时间戳和随机字符串
                    alarm.setAlarmId(timestamp + randomPart.toString());
                    alarm.setCreateTime(DateUtils.getNowDate());
                    alarm.setAlarmType("0x01");  //默认
                    alarm.setNotes(deviceName + "有溺水警告");
                    alarm.setStatus(0);
                    // 插入数据
                    int result = alarmDao.insertAlarm(alarm);
                    if (result > 0) {
                        return ResponseUtil.success("添加警报成功");
                    } else {
                        return ResponseUtil.error("添加警报失败");
                    }
                }
            } catch (Exception e) {
                log.error("添加警报异常", e);
                return ResponseUtil.error("添加警报异常：" + e.getMessage());
            }
        } else {
            return ResponseUtil.error("摄像头id不能为空");
        }
    }


//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public ResponseUtil updateAlarm(Alarm alarm) {
//        try {
//            // 检查警报是否存在
//            Alarm existingAlarm = alarmDao.getAlarmById(alarm.getId());
//            if (existingAlarm == null) {
//                return ResponseUtil.error("警报不存在");
//            }
//
//            // 如果修改了警报ID，需要检查新ID是否已存在
//            if (alarm.getAlarmId() != null && !alarm.getAlarmId().equals(existingAlarm.getAlarmId())) {
//                Alarm alarmWithNewId = alarmDao.getAlarmById(alarm.getAlarmId());
//                if (alarmWithNewId != null) {
//                    return ResponseUtil.error("新的警报ID已存在");
//                }
//            }
//
//            // 设置更新时间
//            alarm.setUpdateTime(new Date());
//
//            // 更新数据
//            int result = alarmDao.updateAlarm(alarm);
//            if (result > 0) {
//                return ResponseUtil.success("更新警报成功");
//            } else {
//                return ResponseUtil.error("更新警报失败");
//            }
//        } catch (Exception e) {
//            log.error("更新警报异常", e);
//            return ResponseUtil.error("更新警报异常：" + e.getMessage());
//        }
//    }


    @Override
    public ApiResponse getAllAlarms(Alarm alarm) {
        try {
            int pageNum = 1;
            if (alarm.getPageNum() != null) {
                pageNum = alarm.getPageNum();
            }
            int pageSize = 1000;
            if (alarm.getPageSize() != null) {
                pageSize = alarm.getPageSize();
            }
            // 设置分页
            PageHelper.startPage(pageNum, pageSize);
            List<Alarm> alarms = alarmDao.findAll(alarm);
            PageInfo<Alarm> pageInfo = new PageInfo<>(alarms);
            return ResponseUtil.success(pageInfo);
        } catch (Exception e) {
            log.error("查询警报列表异常", e);
            return ResponseUtil.error("查询警报列表异常：" + e.getMessage());
        }

    }

    @Override
    public ApiResponse updateStatus(String alarmId) {
        int i = alarmDao.updateAlarm(alarmId);
        return ResponseUtil.success();
    }
}

